from django.db.models import Q
from django.http import Http404
from rest_framework import status
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from recruits.models import Recruit, Enterprise, City
from recruits.serializers import RecruitSerializer, EnterpriseSerializer, CitySerializer, EntSerializer, ReSerializer


class PermissionViewSet(ListAPIView):

    queryset = Recruit.objects.all()
    serializer_class = RecruitSerializer


class EnterpriseViewSet(ListAPIView):
    queryset = Enterprise.objects.all()
    serializer_class = EnterpriseSerializer


class CityViewSet(ListAPIView):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class RecruitsViewSet(RetrieveAPIView):
    queryset = Recruit.objects.all()
    serializer_class = ReSerializer


class KeywordViewSet(APIView):
    def post(self, request):
        cityname = request.data.get('cityname')
        keyword = request.data.get('keyword')
        # Content_Type = request.META.get("HTTP_CONTENT_TYPE")
        # print(request.META)

        if keyword:

            jobs = Recruit.objects.filter(Q(jobname__contains=keyword) & Q(city=cityname))
        else:
            jobs = Recruit.objects.filter(city=cityname)
        serializer = RecruitSerializer(jobs, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)


class AVisitViewSet(APIView):
    def put(self, request, pk):
        try:
            job = Recruit.objects.get(pk=pk)
        except Exception:
            raise Http404
        job.visits += 1
        job.save()
        return Response({
                    "message":"更新成功",
                    "success":True
                        })


# class CollectViewSet(APIView):
#     def post(self, request, pk):
#         user = request.user
#         try:
#             job = Recruit.objects.get(pk=pk)
#         except Exception:
#             raise Http404
#         job.users.add(user)
#         job.save()
#         return Response({
#                     "message":"更新成功",
#                     "success":True
#                         })


class EnterpriseView(RetrieveAPIView):
    queryset = Enterprise.objects.all()
    serializer_class = EntSerializer


class EVisitViewSet(APIView):
    def put(self, request, pk):
        try:
            name = Enterprise.objects.get(pk=pk)
        except Exception:
            raise Http404
        name.visits += 1
        name.save()
        return Response({
                    "message":"更新成功",
                    "success":True
                        })











